package com.example.demo.Service;

import com.example.demo.Qo.VerifyQo;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Service;

import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

/**
 * VerifyService
 *
 * @blame Android Team
 */
public class VerifyService {
    private static final String APP_ID = "2061024774";
    private static final String APP_SECRET = "05U1CrPTVtZa2q3RyuNJGLA";
    private static final String VERIFY_URI = "https://ssl.captcha.qq.com/ticket/verify?aid=%s&AppSecretKey=%s&Ticket=%s&Randstr=%s&UserIP=%s";

    public static int verifyTicket(String ticket, String rand, String userIp) {
        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpGet httpGet;
        CloseableHttpResponse response = null;
        try {
            httpGet = new HttpGet(String.format(VERIFY_URI,
                    APP_ID,
                    APP_SECRET,
                    URLEncoder.encode(ticket, StandardCharsets.UTF_8),
                    URLEncoder.encode(rand, StandardCharsets.UTF_8),
                    URLEncoder.encode(userIp, StandardCharsets.UTF_8)
            ));
            response = httpclient.execute(httpGet);

            HttpEntity entity = response.getEntity();
            if (entity != null) {
                String res = EntityUtils.toString(entity);

                System.out.println(res);

                VerifyQo verifyQo = new ObjectMapper().readValue(res,VerifyQo.class);
//                // 返回码
                int code = Integer.parseInt(verifyQo.getResponse());
//                // 恶意等级
                int evilLevel = Integer.parseInt(verifyQo.getEvil_level());

                // 验证成功
                if (code == 1) {
                    return evilLevel;
                }

            }
        } catch (java.io.IOException e) {
            // 忽略
        } finally {
            try {
                assert response != null;
                response.close();
            } catch (Exception ignore) {
            }
        }

        return -1;
    }

    public static void main(String[] args) throws Exception {
        verifyTicket("t02zI_ClnOI65gLZMXbCYvsfY3D5DBL9Ivdk-1TOOtd2P-xe1IcFzegvFgoZOux6OsnzIgcNwrcQTA67zIzHwM-7sEztAfH5aZNkLOxvqDbTHu8GGHUROE9bw**", "@FFF", "");
    }
}

